package com.example.chat.interceptor;

import com.example.chat.utils.JwtUtil;
import com.example.chat.utils.UserHolder;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.time.LocalDateTime;


@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        response.setHeader("Access-Control-Allow-Origin", "http://localhost:8081");
//        response.setHeader("Access-Control-Allow-Origin", "http://106.53.220.44:8081");
        response.setHeader("Access-Control-Allow-Origin", "http://117.72.161.67:8081");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        // 如果是预检请求，直接返回响应
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return false;
        }

        //1、从请求头中获取令牌
        String token = request.getHeader("authorization");

        //2、校验令牌
        try {
            Claims claims = JwtUtil.parseJWT(token);
            Long userId = Long.valueOf(claims.get("user_id").toString());
//            log.info("当前用户的id：{}", userId);
            //3、通过，放行
            UserHolder.setCurrentId(userId);
            //4、uv统计
//            log.info("uv统计执行......");
//
//            LocalDateTime now = LocalDateTime.now();
//            StringBuilder builder = new StringBuilder();
//            String dateKey = builder.append("admin:").append(now.getYear()).append(":")
//                    .append(now.getMonthValue()).append(":")
//                    .append(now.getDayOfMonth()).append(":UV").toString();
//            stringRedisTemplate.opsForHyperLogLog().add(dateKey,userId.toString());
//            Long size = stringRedisTemplate.opsForHyperLogLog().size(dateKey);
//            log.info("今日访客量：{}",size);
            return true;
        } catch (Exception ex) {
            //4、不通过，响应401状态码
            response.setStatus(401);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeCurrentId();
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
